#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
多Handler定时任务使用示例

本示例展示如何配置和使用支持多Handler的定时任务系统
"""

import sys
import os

# 添加src目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'src'))

from scheduler_app import main
from sync_handler import sync_task, incremental_sync_task
from cleanup_handler import data_cleanup_task, archive_old_data_task
from notify import send_sync_notification, send_error_alert


def manual_sync_example():
    """
    手动执行同步任务示例
    """
    print("=== 手动执行同步任务 ===")
    
    try:
        # 执行同步任务（现在从配置文件读取数据库配置）
        result = sync_task(
            batch_size=500,
            timeout=300,
            retry_count=3
        )
        print(f"同步结果: {result}")
    except Exception as e:
        print(f"同步失败: {e}")


def manual_incremental_sync_example():
    """
    手动执行增量同步任务示例
    """
    print("\n=== 手动执行增量同步任务 ===")
    
    try:
        # 执行增量同步任务（现在从配置文件读取数据库配置）
        result = incremental_sync_task(
            hours_back=2,
            batch_size=500,
            retry_count=2
        )
        print(f"增量同步结果: {result}")
    except Exception as e:
        print(f"增量同步失败: {e}")


def manual_cleanup_example():
    """
    手动执行数据清理任务示例
    """
    print("\n=== 手动执行数据清理任务 ===")
    
    try:
        # 执行数据清理任务（试运行模式）
        result = data_cleanup_task(
            days_to_keep=30,
            batch_size=1000,
            dry_run=True  # 试运行，不实际删除数据
        )
        print(f"数据清理结果: {result}")
    except Exception as e:
        print(f"数据清理失败: {e}")


def manual_archive_example():
    """
    手动执行数据归档示例
    """
    print("\n=== 手动执行数据归档示例 ===")
    
    try:
        # 执行数据归档任务
        result = archive_old_data_task(
            days_to_archive=90,
            archive_table_suffix='_archive_2024'
        )
        print(f"数据归档结果: {result}")
    except Exception as e:
        print(f"数据归档失败: {e}")


def config_file_example():
    """
    配置文件使用示例
    """
    print("\n=== 配置文件示例 ===")
    
    config_example = """
# config/config.yaml 配置文件示例

# 全局配置
global:
  log_level: INFO
  log_file: logs/scheduler.log
  notification:
    wechat_work:
      webhook_key: "your-webhook-key-here"
      enabled: true

# Handler任务配置
handlers:
  # 主数据同步任务
  main_sync:
    name: "主数据同步"
    description: "每日凌晨执行的主数据同步任务"
    enabled: true
    schedule:
      cron: "0 2 * * *"  # 每天凌晨2点执行
    handler:
      module: "sync_handler"
      function: "sync_task"
    databases:
      source_db:
        host: "source-db-host"
        port: 3306
        user: "sync_user"
        password: "sync_password"
        database: "source_db"
        charset: "utf8mb4"
      target_db:
        host: "target-db-host"
        port: 3306
        user: "sync_user"
        password: "sync_password"
        database: "target_db"
        charset: "utf8mb4"
      mall_db:
        host: "mall-db-host"
        port: 3306
        user: "sync_user"
        password: "sync_password"
        database: "mall_db"
        charset: "utf8mb4"
    parameters:
      batch_size: 1000
      timeout: 300
      retry_count: 3
      start_date: null  # 如果为null，会使用默认逻辑
      end_date: null

  # 增量同步任务
  incremental_sync:
    name: "增量数据同步"
    description: "每小时执行的增量数据同步"
    enabled: true
    schedule:
      cron: "0 * * * *"  # 每小时执行
    handler:
      module: "sync_handler"
      function: "incremental_sync_task"
    databases:
      source_db:
        host: "source-db-host"
        port: 3306
        user: "sync_user"
        password: "sync_password"
        database: "source_db"
        charset: "utf8mb4"
      target_db:
        host: "target-db-host"
        port: 3306
        user: "sync_user"
        password: "sync_password"
        database: "target_db"
        charset: "utf8mb4"
    parameters:
      hours_back: 2  # 向前追溯2小时
      batch_size: 500
      retry_count: 2

  # 数据清理任务
  data_cleanup:
    name: "数据清理"
    description: "每周执行的数据清理任务"
    enabled: true
    schedule:
      cron: "0 3 * * 0"  # 每周日凌晨3点执行
    handler:
      module: "cleanup_handler"
      function: "data_cleanup_task"
    databases:
      target_db:
        host: "target-db-host"
        port: 3306
        user: "cleanup_user"
        password: "cleanup_password"
        database: "target_db"
        charset: "utf8mb4"
    parameters:
      days_to_keep: 30
      batch_size: 1000
      dry_run: false

  # 数据归档任务
  data_archive:
    name: "数据归档"
    description: "每月执行的数据归档任务"
    enabled: false  # 默认禁用，需要时手动启用
    schedule:
      cron: "0 4 1 * *"  # 每月1号凌晨4点执行
    handler:
      module: "cleanup_handler"
      function: "archive_old_data_task"
    databases:
      target_db:
        host: "target-db-host"
        port: 3306
        user: "archive_user"
        password: "archive_password"
        database: "target_db"
        charset: "utf8mb4"
    parameters:
      days_to_archive: 90
      archive_table_suffix: "_archive"
    """
    
    print(config_example)


def start_scheduler_example():
    """
    启动调度器示例
    """
    print("\n=== 启动调度器示例 ===")
    print("要启动多Handler调度器，请执行:")
    print("python src/scheduler_app.py")
    print("")
    print("调度器将会:")
    print("1. 读取 config/config.yaml 配置文件")
    print("2. 动态加载各个Handler模块")
    print("3. 根据cron表达式调度各个任务")
    print("4. 执行任务并发送通知")
    print("5. 记录详细的执行日志")


if __name__ == "__main__":
    print("多Handler定时任务系统使用示例")
    print("=" * 50)
    
    # 显示配置文件示例
    config_file_example()
    
    # 显示启动调度器的方法
    start_scheduler_example()
    
    # 注意：以下手动执行示例需要实际的数据库连接，请根据实际情况修改配置
    print("\n注意：以下手动执行示例需要实际的数据库连接")
    print("请根据实际情况修改数据库配置后再执行")
    
    # 取消注释以下行来执行手动示例
    # manual_sync_example()
    # manual_incremental_sync_example()
    # manual_cleanup_example()
    # manual_archive_example()